import { Card, Form, Input, Image as AntdImage, AutoComplete, Upload, Space, message, Modal, Select, DatePicker, Divider, Row, Col, InputNumber } from "antd";
import { useModel, history } from "umi";
import { Button, ButtonGroup, Card as SemiCard, List } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconSearch, IconDelete, IconEdit } from "@douyinfe/semi-icons";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { useReactive } from "ahooks";
import { useEffect, useRef, useState } from "react";
import { EditableProTable } from "@ant-design/pro-components";
import { v4 as uuidv4 } from "uuid";

import useAllBrands from "../../hooks/brand/useAllBrands";
import useCreateBrand from "../../hooks/brand/useCreateBrand";
import useUpdateCommodity from "../../hooks/commodities/useUpdateCommodity";

const CommodityEditPage = (props) => {
	const { windowInnerHeight } = useModel("global", (model) => model);
	const { brands, loadAllBrands } = useAllBrands();
	const { updateCommodity } = useUpdateCommodity();
	const { createBrand } = useCreateBrand();

	const [form] = Form.useForm();
	const inputRef = useRef(null);
	const [editableKeys, setEditableRowKeys] = useState([]);

	const state = useReactive({
		brandItems: [],
		brandName: "",
		photoList: [],
		photos: {},
		producer: [],
		submitLoading: false,
	});

	const onFinish = async (values) => {
		updateCommodity(values, (res) => {
			if (res) {
				message.success("成功修改商品信息");
				history.replace("/commodities/list");
			}
		});
	};

	const addBrand = (e) => {
		e.preventDefault();
		createBrand(state.brandName, (res) => {
			if (res) {
				loadAllBrands();
			}
		});
		state.brandName = "";
		setTimeout(() => {
			inputRef.current?.focus();
		}, 0);
	};

	//查看大图
	const onPreview = (file) => {
		state.photos = { previewImage: file.path, visible: true };
	};
	const handleCancel = () => {
		state.photos = { visible: false };
	};

	// 窗口头部：30，应用头：60，页头：59，操作区内边距：24，卡面头：51，卡面脚：56,修正值：4
	const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;
	return (
		<div>
			<SemiCard
				title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>编辑商品</span>}
				headerStyle={{ padding: "10px 14px" }}
				shadows="always"
				bordered={false}
				size="default"
				bodyStyle={{ padding: 0, height: cardBodyHeight }}
				headerExtraContent={
					<Space>
						<Button onClick={() => history.replace("/commodities/list")}>返回</Button>
					</Space>
				}
			>
				<Form form={form} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 15 }} onFinish={onFinish} style={{ marginTop: 10 }}>
					<Row>
						<Col span={24}>
							<Divider orientation="center">商品基本信息</Divider>
						</Col>
						<Col span={8}>
							<Form.Item label="商品名称" name="" rules={[{ required: true }]}>
								<Input />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item label="商品品牌" name="inInda" rules={[{ required: true }]}>
								<Select
									dropdownRender={(menu) => (
										<>
											{menu}
											<Divider style={{ margin: "8px 0" }} />
											<Space style={{ padding: "0 8px 4px" }}>
												<Input
													placeholder="请输入品牌"
													ref={inputRef}
													value={state.brandName}
													onChange={(e) => (state.brandName = e.target.value)}
													onKeyDown={(e) => e.stopPropagation()}
												/>
												<Button theme="borderless" icon={<PlusOutlined />} onClick={addBrand}>
													添加品牌
												</Button>
											</Space>
										</>
									)}
									options={brands.map((item) => ({
										label: item,
										value: item,
									}))}
								/>
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item label="规格型号" name="inInco" rules={[{ required: true }]}>
								<Input />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item label="计量单位" name="inChco" rules={[{ required: true }]}>
								<Input />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item label="国标编码" name="inInno">
								<Input />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item label="内部编码" name="inInnn">
								<Input />
							</Form.Item>
						</Col>

						<Col span={8}>
							<Form.Item label="参考售价" name="inMano">
								<InputNumber style={{ width: 275 }} />
							</Form.Item>
						</Col>
						<Col span={16} pull={2}>
							<Form.Item label="商品描述" name="inAgen">
								<Input />
							</Form.Item>
						</Col>
					</Row>

					<div style={{ position: "absolute", bottom: 40, left: 650 }}>
						<Space>
							<Button loading={state.submitLoading} theme="solid" type="primary" htmlType="submit" style={{ width: "100%" }}>
								保存
							</Button>
							<Button loading={state.submitLoading} theme="solid" type="warning" onClick={() => form.resetFields()}>
								重置
							</Button>
						</Space>
					</div>
				</Form>

				<div style={{ padding: "0 25px 0 15px" }}>
					<EditableProTable
						rowKey="id"
						size="small"
						bordered
						title={() => "产地信息"}
						recordCreatorProps={{ position: "bottom", record: () => ({ id: uuidv4() }) }}
						columns={[
							{ title: "序号", width: 60, align: "center", editable: false, render: (_, r, i) => i + 1 },
							{
								title: "产地区划",
								dataIndex: "itName",
								width: 400,
								valueType: "select",
								valueEnum: {
									省: { text: "湖北省", status: "Success" },
								},
								align: "center",
								formItemProps: () => ({ rules: [{ required: true, message: "此项为必填项" }] }),
							},
							{
								title: "详细地址",
								dataIndex: "itNames",
								fieldProps: () => ({ controls: false, style: { width: "100%" } }),
								align: "center",
								formItemProps: () => ({ rules: [{ required: true, message: "此项为必填项" }] }),
							},
							{
								title: "操作",
								width: 200,
								valueType: "option",
								align: "center",
								render: (text, record, _) => (
									<Space>
										{/* <Button theme="borderless" icon={<IconEdit />} onClick={() => editProducer(record)}></Button> */}
										<Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />} onClick={() => deleteProducer(record)}></Button>
									</Space>
								),
							},
						]}
						value={state.producer}
						editable={{
							type: "multiple",
							onSave: async (rowKey, data) => savaProducer(data),
							actionRender: (row, config, defaultDoms) => [defaultDoms.save, defaultDoms.cancel],
							editableKeys,
							onChange: setEditableRowKeys,
						}}
					/>
				</div>

				<div style={{ marginLeft: 40 }}>
					<Upload
						multiple
						listType="picture-card"
						fileList={state.photoList}
						accept="image/*"
						beforeUpload={async (file, fileList) => {
							const photo = state.photoList.find((item) => item.url === file.path);
							if (!photo) state.photoList = [...state.photoList, { name: file.name, size: file.size, path: file.path, url: file.path }];
							else message.warning("不能上传重复的图片，请重新选择图片");
							return false;
						}}
						onRemove={(file) => {
							state.photoList = state.photoList.filter((item) => item.url !== file.url);
							return false;
						}}
						onPreview={onPreview}
					>
						{state.photoList?.length < 3 && (
							<div>
								<PlusOutlined />
								<div style={{ marginTop: 8 }}>商品图片</div>
							</div>
						)}
					</Upload>
				</div>

				<Modal open={state.photos.visible} footer={null} onCancel={handleCancel}>
					<img alt="加载" style={{ width: "100%", height: "100%" }} src={state.photos.previewImage} />
				</Modal>
			</SemiCard>
		</div>
	);
};

export default CommodityEditPage;
